package jp.co.iris_ltd.twitter;

import java.io.File;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

public class TwitterManager {
    public interface TwitterManagerListner {
        public void onStartOAuth();

        public void onFinishOAuth();

        public void onStartGetToken();

        public void onFinishGetToken();

//        public void onStartTweet();
//        public void onFinishTweet();
    }

    public static final String TAG = "TwitterManager";
    public static final String CALLBACK_URL = "irisphotoeditor://oauth";
    public static final String OAUTH_VERIFIER = "oauth_verifier";
    public static final String KEY_TOKEN = "key_token";
    public static final String KEY_TOKEN_SECRET = "key_token_secret";
    private Context mContext;
    private Twitter mTwitter;
    private RequestToken mRequestToken;
    private String mConsumerKey;
    private String mConsumerKeySecret;
    private TwitterManagerListner mListner;

    public TwitterManager(Context context, String consumerKey, String consumerKeySecret) {
        mContext = context;
        mConsumerKey = consumerKey;
        mConsumerKeySecret = consumerKeySecret;
        try {
            mListner = (TwitterManagerListner) context;
        } catch (ClassCastException e) {
            Log.e(TAG, "Context mast implements 'TwitterManagerListner'.");
        }
    }

    public boolean isOAuthed() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        String token = prefs.getString(KEY_TOKEN, "");
        String tokenSecret = prefs.getString(KEY_TOKEN_SECRET, "");
        return !(token.length() <= 0 || tokenSecret.length() <= 0);
    }

    public void doOAuth() {
        doOAuth(false);
    }

    public void doOAuth(boolean forceOption) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        String token = prefs.getString(KEY_TOKEN, "");
        String tokenSecret = prefs.getString(KEY_TOKEN_SECRET, "");
        if (forceOption || (token.length() <= 0 || tokenSecret.length() <= 0)) {
            mTwitter = new TwitterFactory().getInstance();
            mTwitter.setOAuthConsumer(mConsumerKey, mConsumerKeySecret);
            if (mListner != null) {
                mListner.onStartOAuth();
            }

            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... params) {
                    String url = "";
                    try {
                        mRequestToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
                        url = mRequestToken.getAuthorizationURL();
                    } catch (TwitterException e) {
                        Log.e(TAG, e.toString(), e);
                    }
                    return url;
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(result)));
                    if (mListner != null) {
                        mListner.onFinishOAuth();
                    }

                }
            }.execute();
        }
    }

    public void setKeyToken(String KeyToken, String KeyTokenSecret) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_TOKEN, KeyToken);
        editor.putString(KEY_TOKEN_SECRET, KeyTokenSecret);
        editor.commit();
    }

    public void setKeyToken(final Uri uri) {

        if (uri != null && uri.toString().startsWith(TwitterManager.CALLBACK_URL)) {
            if (mListner != null) {
                mListner.onStartGetToken();
            }

            new AsyncTask<Void, Void, Void>() {
                AccessToken accessToken;

                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        String verifier = uri.getQueryParameter(TwitterManager.OAUTH_VERIFIER);
                        accessToken = mTwitter.getOAuthAccessToken(mRequestToken, verifier);

                    } catch (TwitterException e) {
                        Log.e(TAG, e.toString(), e);
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    setKeyToken(accessToken.getToken(), accessToken.getTokenSecret());
                    if (mListner != null) {
                        mListner.onFinishGetToken();
                    }
                };
            }.execute();
        }
    }

    public boolean tweet(final String tweet) {
        boolean result = true;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
        String token = prefs.getString(KEY_TOKEN, null);
        String tokenSecret = prefs.getString(KEY_TOKEN_SECRET, null);
        AccessToken accessToken = new AccessToken(token, tokenSecret);
        mTwitter = new TwitterFactory().getInstance();
        mTwitter.setOAuthConsumer(mConsumerKey, mConsumerKeySecret);
        mTwitter.setOAuthAccessToken(accessToken);
        accessToken = null;
        try {
            mTwitter.updateStatus(tweet);
        } catch (Exception e) {
            android.util.Log.e("TwitterException", e.toString(), e);
            result = false;
        }

        return result;
    }

    public boolean tweet(final String tweet, String imageFilePath, boolean forceOption) {
        boolean result = true;
        final File photoFile = new File(imageFilePath);
        if (imageFilePath == null || imageFilePath == "" || !photoFile.exists()) {
            if (forceOption) {
                result = tweet(tweet);
            } else {
                result = false;
            }
        } else {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
            String token = prefs.getString(KEY_TOKEN, "");
            String tokenSecret = prefs.getString(KEY_TOKEN_SECRET, "");
            ConfigurationBuilder confbuilder = new ConfigurationBuilder();
            confbuilder.setOAuthAccessToken(token);
            confbuilder.setOAuthAccessTokenSecret(tokenSecret);
            confbuilder.setOAuthConsumerKey(mConsumerKey);
            confbuilder.setOAuthConsumerSecret(mConsumerKeySecret);
            confbuilder.setMediaProvider("TWITTER");
            Configuration conf = confbuilder.build();
            ImageUpload imageUpload = new ImageUploadFactory(conf).getInstance();
            try {
                imageUpload.upload(photoFile, tweet);
            } catch (Exception e) {
                android.util.Log.e("TwitterException", e.toString(), e);
                result = false;
            }
        }
        return result;
    }

}
